const UserApi = require('../../../api/user.js');
const regExpUtil = require('../../utils/regExp.js');
const commonUtil = require('../../../utils/common')

Page({
  data: {
    _userInfo: null,
    formModel: {
      username: null,
    }
  },

  onLoad(options) {},
  onReady() {},
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({_userInfo: userInfo});
  },
  onHide() {},
  onUnload() {},

  buttonClick(){
    if (this.data._userInfo.username) {
      wx.navigateBack({delta: 1});
    } else {
      if (!this.data.formModel.username) {
        wx.showToast({icon: 'none', title: '请输入用户名'});
      } else if (this.data.formModel.username && !regExpUtil.isLegalUserName(this.data.formModel.username)) {
        wx.showToast({icon: 'none', title: '用户名由3~20个字母或数字组成，字母开头'});
      } else {
        let that = this;
        UserApi.setUsername({username: this.data.formModel.username}).then(res=>{
          if (res.retCode == '000000' && res.errCode == '000000') {
            wx.showToast({icon:'success', title: res.errMsg})
            this.setData({['formModel.username']: null})
            commonUtil.getLoginUser()
            setTimeout(()=>{
              let userInfo = wx.getStorageSync('userInfo');
              that.setData({_userInfo: userInfo})
            }, 200)
          } else {
            wx.showToast({icon: 'error', title: res.errMsg})
          }
        })
      }
    }
  },
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'username') {
      this.setData({['formModel.username']: value})
    }
  },
  
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})